/**
 * 
 */
package array.passed2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xyyi
 *
 */
public class TextJustification {

	/**
	Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

	You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.

	Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

	For the last line of text, it should be left justified and no extra space is inserted between words.

	For example,
	words: ["This", "is", "an", "example", "of", "text", "justification."]
	L: 16.

	Return the formatted lines as:

	[
	"This    is    an",
	"example  of text",
	"justification.  "
	]

	Note: Each word is guaranteed not to exceed L in length.
	Corner Cases:

	A line other than the last line might contain only one word. What should you do in this case?
	In this case, that line should be left-justified.
	 */
	public ArrayList<String> fullJustify(String[] words, int L) {

		ArrayList<String> result = new ArrayList<String>();
		final StringBuilder sb = new StringBuilder();
		int start = 0, end = 0, currLen = 0;
		while (end < words.length) {
			currLen += start == end ? words[end].length()
					: words[end].length() + 1;
			if (currLen >= L) {
				if (currLen > L)
					currLen -= words[end--].length() + 1;

				if (start == end) {
					sb.append(words[start]);
					for (int i = 0; i < L - currLen; i++) {
						sb.append(' ');
					}
				} else {
					int numOfWord = end - start + 1;
					int spaceAvg = (L - (currLen - numOfWord + 1))
							/ (numOfWord - 1);
					int spaceLeft = (L - (currLen - numOfWord + 1))
							% (numOfWord - 1);
					while (start < end) {
						sb.append(words[start++]);
						int padding = spaceLeft-- > 0 ? spaceAvg + 1 : spaceAvg;
						for (int i = 0; i < padding; i++) {
							sb.append(' ');
						}
					}
					sb.append(words[start]);
				}

				result.add(sb.toString());
				sb.setLength(0);
				currLen = 0;
				start++;
				end++;
			} else { // currLen < L
				if (end == words.length - 1) {
					while (start < end) {
						sb.append(words[start++]).append(' ');
					}
					sb.append(words[start]);
					for (int i = 0, size = L - sb.length(); i < size; i++) {
						sb.append(' ');
					}
					result.add(sb.toString());
					sb.setLength(0);
					currLen = 0;
					start++;
				}

				end++;
			}
		}

		return result;
	}

	public ArrayList<String> fullJustify2(String[] words, int L) {
		ArrayList<String> result = new ArrayList<String>();
		if (words == null || words.length == 0)
			return result;

		final StringBuilder sb = new StringBuilder();
		for (int i = 0; i < words.length; i++) {
			int start = i, end = i, lineSize = 0;
			while (lineSize <= L && i < words.length) {
				lineSize += words[i++].length() + 1;
			}
			if (lineSize - 1 > L) {
				lineSize -= words[--i].length() + 1;
			}

			end = --i;
			boolean isLastLine = end == words.length - 1;

			int intervals = end - start; // the of intervals between all words in this line
			int totalSpace = L - (lineSize - intervals - 1);
			int avgSpace = 0, extraSpace = 0;
			if (intervals > 0) {
				avgSpace = totalSpace / (end - start);
				extraSpace = totalSpace % (end - start);
			}
			if (isLastLine) {
				for (int j = start; j < end; j++) {
					sb.append(words[j]).append(' ');
				}
				sb.append(words[end]);
				addSpaces(sb, L - sb.length());
			} else {
				for (int j = start; j < end; j++) {
					sb.append(words[j]);
					addSpaces(sb, avgSpace);
					if (extraSpace > 0) {
						sb.append(' ');
						extraSpace--;
					}
				}
				sb.append(words[end]);
				addSpaces(sb, L - sb.length());
			}
			result.add(sb.toString());
			sb.setLength(0);
		}

		return result;
	}

	/**
	 * Best solution
	 * http://fisherlei.blogspot.com/2013/01/leetcode-text-justification.html
	 */
	public List<String> fullJustify6(String[] words, int maxWidth) {
		List<String> result = new ArrayList<>();
		if (words == null || words.length == 0)
			return result;
		
		int wi = 0;
		while (wi < words.length) {
			int start = wi, lineLen = -1; // lineLen is ended with a word where no extra word to be added with a leading space
			                              // "a b c" with maxWidth 5 or "a b c" with maxWidth 6
			while (wi < words.length && lineLen + words[wi].length() + 1 <= maxWidth) {
				lineLen += words[wi++].length() + 1;
			}
			
			int end = wi - 1;
			boolean isLastLine = end == words.length - 1;
			int intervals = end - start; // the number of intervals between all words in this line,
			// interval is the spaces between two words;
			int totalSpaces = maxWidth - (lineLen - intervals);
			int avgSpaces = intervals > 0 ? totalSpaces / intervals : 0;
			int extraSpaces = intervals > 0 ? totalSpaces % intervals : 0;
			StringBuilder sb = new StringBuilder();
			for (int i = start; i < end; i++) {
				sb.append(words[i]);
				if (isLastLine) {
					sb.append(' ');
				}
				else {
					addSpaces(sb, avgSpaces);
					if (extraSpaces > 0) {
						sb.append(' ');
						extraSpaces--;
					}
				}
			}
			sb.append(words[end]);
			addSpaces(sb, maxWidth - sb.length());
			result.add(sb.toString());			
		}
		
		return result;
	}	
	
	public List<String> fullJustify3(String[] words, int maxWidth) {
		ArrayList<String> result = new ArrayList<String>();
		if (words == null || words.length == 0)
			return result;

		final StringBuilder sb = new StringBuilder();
		for (int i = 0; i < words.length; i++) {
			int start = i, end = i, lineSize = 0;
			while (lineSize <= maxWidth && i < words.length) {
				lineSize += words[i++].length() + 1;
			}
			if (lineSize - 1 > maxWidth) {
				lineSize -= words[--i].length() + 1; //i is the last word should be removed
			}

			end = --i; // move i to the word before removing one.
			boolean isLastLine = end == words.length - 1;

			int intervals = end - start; // the number of intervals between all words in this line,
											// interval is the spaces between two words;
			int totalSpace = maxWidth - (lineSize - intervals - 1);
			int avgSpace = 0, extraSpace = 0;
			if (intervals > 0) {
				avgSpace = totalSpace / intervals;
				extraSpace = totalSpace % intervals;
			}

			for (int j = start; j < end; j++) {
				sb.append(words[j]);
				if (isLastLine) {
					sb.append(' ');
				} else {
					addSpaces(sb, avgSpace);
					if (extraSpace > 0) {
						sb.append(' ');
						extraSpace--;
					}
				}
			}
			sb.append(words[end]);
			addSpaces(sb, maxWidth - sb.length());
			result.add(sb.toString());
			sb.setLength(0);
		}

		return result;
	}

	private void addSpaces(StringBuilder sb, int n) {
		for (int i = 0; i < n; i++) {
			sb.append(' ');
		}
	}

	public List<String> fullJustify4(String[] words, int maxWidth) {
		List<String> result = new ArrayList<>();
		if (words == null || words.length == 0)
			return result;
		
		int wi = 0;
		while (wi < words.length) {
			int start = wi, lineLen = -1;
			while (wi < words.length && lineLen + words[wi].length() + 1 <= maxWidth) {
				lineLen += words[wi++].length() + 1;
			}
			
			int end = wi - 1;
			boolean isLastLine = end == words.length - 1;
			int intervals = end - start;
			int totalSpaces = maxWidth - (lineLen - intervals);
			int avgSpaces = intervals > 0 ? totalSpaces / intervals : 0;
			int extraSpaces = intervals > 0 ? totalSpaces % intervals : 0;
			StringBuilder sb = new StringBuilder();
			for (int i = start; i < end; i++) {
				sb.append(words[i]);
				if (isLastLine) {
					sb.append(' ');
				}
				else {
					addSpaces(sb, avgSpaces);
					if (extraSpaces > 0) {
						sb.append(' ');
						extraSpaces--;
					}
				}
			}
			sb.append(words[end]);
			addSpaces(sb, maxWidth - sb.length());
			result.add(sb.toString());			
		}
		
		return result;
	}
	
	public List<String> fullJustify5(String[] words, int maxWidth) {
		ArrayList<String> result = new ArrayList<String>();
		if (words == null || words.length == 0)
			return result;

		final StringBuilder sb = new StringBuilder();
		for (int i = 0; i < words.length; i++) {
			int start = i, end = i, lineLen = 0;
			while (i < words.length && lineLen + words[i].length() <= maxWidth) {
				lineLen += words[i++].length();
				if (lineLen + 1 <= maxWidth)
					lineLen++;
			}

			end = --i; // move i to the word before removing one.
			boolean isLastLine = end == words.length - 1;

			int intervals = end - start; // the number of intervals between all words in this line,
											// interval is the spaces between two words;
			int totalSpace = maxWidth - (lineLen - intervals);
			int avgSpace = 0, extraSpace = 0;
			if (intervals > 0) {
				avgSpace = totalSpace / intervals;
				extraSpace = totalSpace % intervals;
			}

			for (int j = start; j < end; j++) {
				sb.append(words[j]);
				if (isLastLine) {
					sb.append(' ');
				} else {
					addSpaces(sb, avgSpace);
					if (extraSpace > 0) {
						sb.append(' ');
						extraSpace--;
					}
				}
			}
			sb.append(words[end]);
			addSpaces(sb, maxWidth - sb.length());
			result.add(sb.toString());
			sb.setLength(0);
		}

		return result;
	}
	
	/**
	 * 
	 */
	public TextJustification() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TextJustification tj = new TextJustification();
		//String[] words = { "Listen", "to", "many,", "speak", "to", "a", "few." };
		String[] words = {"a","b","c","d","e"};
		int maxWidth = 3;
		tj.fullJustify5(words, 3);
	}
}
